package com.example.myimageshare.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.customview.widget.ViewDragHelper;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;


import com.example.myimageshare.Main2Activity;
import com.example.myimageshare.entity.User;
import com.example.myimageshare.R;
import com.example.myimageshare.service.Impl.UserSeviceImpl;
import com.example.myimageshare.service.UserSercice;
import com.google.android.material.navigation.NavigationView;

import java.io.File;
import java.lang.reflect.Field;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

//  初始化变量
    private Toolbar toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private NavigationView nView;


//  Framement控制相关
    FragmentTransaction fragmentTransaction;
    FragmentManager manager;
    Fragment fl,fragment_1,fragment_2,fragment_3;

    //Layout控制相关


//  数据
    User user = null;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Bmob默认初始化
        Bmob.initialize(this,"fe6db2f6fc375fcd7ef673b08de659dc");





//        //设置上传文件分片及片大小
//        BmobConfig config = new BmobConfig.Builder(this)
//                .setConnectTimeout(30)
//                .setUploadBlockSize(500*1024)
//                .build();
//        Bmob.initialize(config); //函数与官方文档有所改动
//        //尝试修改一行数据
//        user.setUserName("wwwxy");
//        user.update("62d398468a", new UpdateListener() {
//            @Override
//            public void done(BmobException e) {
//                if(e==null){
//                    Toast.makeText(MainActivity.this,
//                            "更新成功："+user.getUpdatedAt(),
//                            Toast.LENGTH_SHORT).show();
//                    System.out.println("更新情况："+user.getUpdatedAt());
//                }else{
//                    Toast.makeText(MainActivity.this,
//                            "更新失败 ："+e.getMessage(),
//                            Toast.LENGTH_SHORT).show();
//
//                }
//            }
//        });

        //尝试删除一行数据
//        user.setObjectId("eadbdcb7f8");
////        user.delete(new UpdateListener() {
////            @Override
////            public void done(BmobException e) {
////                if(e==null){
////                    Toast.makeText(MainActivity.this,
////                            "删除成功："+user.getUpdatedAt(),
////                            Toast.LENGTH_SHORT).show();
////                    System.out.println("删除情况："+user.getUpdatedAt());
////                }else{
////                    Toast.makeText(MainActivity.this,
////                            "删除失败 ："+e.getMessage(),
////                            Toast.LENGTH_SHORT).show();
////
////                }
////            }
////        });

//        //上传文件测试
//        String picPath = "storage/emulated/0/$MuMu共享文件夹/MuMu20210826150846.png";
//        final BmobFile bmobFile = new BmobFile(new File(picPath));
//        bmobFile.uploadblock(new UploadFileListener() {
//            @Override
//            public void done(BmobException e) {
//                if (e==null) {
//                    System.out.println("上传文件成功：" + bmobFile.getFileUrl());
//                }else {
//                    System.out.println("上传文件失败："+e.getMessage());
//                }
//            }
//        });



        initView();
        initData();
        initListener();
//        System.out.println("活动得到数据:"+user_Info.get(0).getUserName());
        //获取管理
        manager = getSupportFragmentManager();
        //实例化fragment
        fragment_1 = new Fragment_1();
        fragment_2 = new Fragment_2();
        fragment_3 = new ImageFragment();



        //打开返回键监听
        mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,
                toolbar, R.string.open, R.string.close){
            @Override
            public void onDrawerOpened(View drawerView){
                super.onDrawerOpened(drawerView);

            }
            @Override
            public void onDrawerClosed(View drawerView){
                super.onDrawerClosed(drawerView);
            }
        };
        setDrawerLeftEdgeSize(this,mDrawerLayout,1);
        mDrawerToggle.syncState();
        //setDrawerListener弃用
        mDrawerLayout.addDrawerListener(mDrawerToggle);


        //状态栏沉浸
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){

            WindowManager.LayoutParams barLayoutParams=getWindow()
                    .getAttributes();
            barLayoutParams.flags=(WindowManager
                    .LayoutParams.FLAG_TRANSLUCENT_STATUS|barLayoutParams.flags);

        }

        //设置适配器
        //默认打开第一个页面
        selectFragment(0);

    }
    /*全屏滑动
    * */
    private void setDrawerLeftEdgeSize (Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null) return;
        try {
            // 找到 ViewDragHelper 并设置 Accessible 为true
            Field leftDraggerField =
                    drawerLayout.getClass().getDeclaredField("mLeftDragger");//Right
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);

            // 找到 edgeSizeField 并设置 Accessible 为true
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);

            // 设置新的边缘大小
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (displaySize.x *
                    displayWidthPercentage)));
        } catch (NoSuchFieldException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
    }

    /*页面选择
     * */
    private void selectFragment(int index){
        //开启Fragment事务
        FragmentTransaction transaction = manager.beginTransaction();
        fragmentTransaction = transaction;
//        隐藏上次的Fragment
        hideFragment(transaction);
        switch (index){
            case 0:
                //为空添加
                if(!fragment_1.isAdded()){
                    //实例化
                    fragment_1 = new Fragment_1();
                    //添加
                    transaction.add(R.id.Container_content,fragment_1);
                }else {
                    //不为空显示
                    transaction.show(fragment_1);
                }
                break;
            case 1:
                if(!fragment_2.isAdded()){
                    fragment_2 = new Fragment_2();
                    transaction.add(R.id.Container_content,fragment_2);
                }else {
                    transaction.show(fragment_2);
                }
                break;
            case 2:
                if(!fragment_3.isAdded()){
                    fragment_3 = new ImageFragment();
                    transaction.add(R.id.Container_content,fragment_3);
                }else {
                    transaction.show(fragment_3);
                }
                break;
        }
        //提交事务
        transaction.commit();

    }

    public void initView(){
        //绑定控件
//        ivAppImage = findViewById(R.id.iv_main);
        toolbar = (Toolbar) findViewById(R.id.tl_custom);
        mDrawerLayout = findViewById(R.id.dl_left);
//        lvLeftMenu = findViewById(R.id.lv_left_menu);
        nView = findViewById(R.id.nav_view);


        //设置ToolBar标题及颜色
        toolbar.setTitleTextColor(Color.BLACK);
        setSupportActionBar(toolbar);
        //设置返回键
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    public void initData(){
//        item = getResources().getStringArray(R.array.list_item);
        //设置菜单列表
//        arrayAdapter = new ArrayAdapter(this,
//                android.R.layout.simple_list_item_1,item);
        nView.setNavigationItemSelectedListener(this);



    }

/*打开相关触发事件*/
    public void initListener(){
////        尝试获取用户信息
//        final BmobQuery<User> bmobQuery = new BmobQuery<User>();
//        bmobQuery.getObject("2d844ece95", new QueryListener<User>() {
//            @Override
//            public void done(User user, BmobException e) {
//                if(e==null){
//                    Toast.makeText(MainActivity.this,
//                            "查询成功："+user.toString(),
//                            Toast.LENGTH_SHORT).show();
//                    System.out.println(user.getUserName());
//                }else{
//                    Toast.makeText(MainActivity.this,
//                            "查询数据失败 ："+e.getMessage(),
//                            Toast.LENGTH_SHORT).show();
//
//                }
//            }
//        });





////      尝试添加用户、及头像
//        final String picPath = "/storage/emulated/0/$MuMu共享文件夹/MuMu20210823142912.png";
//        Bitmap bmp= BitmapFactory.decodeFile(picPath);
//        ImageView iv = findViewById(R.id.img1);
//        iv.setImageBitmap(bmp);
//
//        final BmobFile bmobFile = new BmobFile(new File(picPath));
//        user.setHeadImg(bmobFile);
//        user.getHeadImg().uploadblock(new UploadFileListener() {
//            @Override
//            public void done(BmobException e) {
//                if (e==null) {
//                    System.out.println("上传文件成功：");
//                    user.setUserName("weiyiyi");
//                    user.setPassword("123456");
//                    user.save(new SaveListener<String>() {
//                        @Override
//                        public void done(String s, BmobException e) {
//                            if (e==null){
//                                Toast.makeText(MainActivity.this,
//                                        "添加数据成功，返回object为："+s,
//                                        Toast.LENGTH_SHORT).show();
//                            }else {
//                                Toast.makeText(MainActivity.this,
//                                        "添加数据失败 ："+e.getMessage(),
//                                        Toast.LENGTH_SHORT).show();
//                            }
//                        }
//                    });
//                }else {
//                    System.out.println("上传文件失败："+e.getMessage());
//                }
//            }
//        });


    }

    /*单一栈模式*/
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //在这里处理intent传回来的数据
    }

    /*隐藏非空Fragment
    * */
    private void hideFragment(FragmentTransaction transaction){
        if(fragment_1 != null){
            transaction.hide(fragment_1);
        }
        if (fragment_2 != null) {
            transaction.hide(fragment_2);
        }
        if (fragment_3 != null) {
            transaction.hide(fragment_3);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        String str = item.getTitle().toString();
        System.out.println(str);
        Toast.makeText(MainActivity.this,str,
                Toast.LENGTH_SHORT).show();
        //页面选择
        switch (item.getItemId()){
            case R.id.nav_upload:
//                selectFragment(0);
                //假设得到用户登录登录信息，taken
                Intent intent = new Intent(this,UploadActivity.class);
                intent.putExtra("msg","tanken");
                startActivity(intent);
                break;
            case R.id.nav_clean:
                selectFragment(1);
                break;
            case R.id.nav_mark:
                selectFragment(2);
            default:
                break;
        }

        return true;
    }

}
